# -*- coding: utf-8 -*-

import logging
from odoo import models, fields, api
from odoo.exceptions import UserError

_logger = logging.getLogger(__name__)


class DeviceInitWizard(models.TransientModel):
    """Device API 初始化向导"""
    _name = 'device.init.wizard'
    _description = 'Device API 初始化向导'

    # 状态字段
    init_status = fields.Selection([
        ('not_init', '未初始化'),
        ('partial', '部分初始化'),
        ('completed', '已完成'),
        ('error', '初始化错误')
    ], string='总体状态', default='not_init')
    
    api_config_status = fields.Boolean('API配置', default=False)
    permission_status = fields.Boolean('权限数据', default=False)
    role_status = fields.Boolean('角色数据', default=False)
    department_status = fields.Boolean('部门数据', default=False)
    post_status = fields.Boolean('岗位数据', default=False)
    view_status = fields.Boolean('视图文件', default=False)
    
    init_log = fields.Text('初始化日志', readonly=True)

    @api.model
    def default_get(self, fields):
        """默认获取当前状态"""
        res = super().default_get(fields)
        self._check_init_status()
        return res

    def _check_init_status(self):
        """检查初始化状态"""
        log_lines = ['=== Device API 状态检查 ===']
        
        # 检查API配置
        api_configs = self.env['device.api.config'].search([])
        self.api_config_status = len(api_configs) >= 4
        log_lines.append(f'API配置: {"✓" if self.api_config_status else "✗"} ({len(api_configs)} 项)')
        
        # 检查权限数据
        permissions = self.env['device.permission'].search([])
        self.permission_status = len(permissions) >= 5
        log_lines.append(f'权限数据: {"✓" if self.permission_status else "✗"} ({len(permissions)} 项)')
        
        # 检查角色数据
        roles = self.env['device.user.role'].search([])
        self.role_status = len(roles) >= 2
        log_lines.append(f'角色数据: {"✓" if self.role_status else "✗"} ({len(roles)} 项)')
        
        # 检查部门数据
        departments = self.env['device.department'].search([])
        self.department_status = len(departments) >= 3
        log_lines.append(f'部门数据: {"✓" if self.department_status else "✗"} ({len(departments)} 项)')
        
        # 检查岗位数据
        posts = self.env['device.user.post'].search([])
        self.post_status = len(posts) >= 5
        log_lines.append(f'岗位数据: {"✓" if self.post_status else "✗"} ({len(posts)} 项)')
        
        # 检查视图状态
        views = self.env['ir.ui.view'].search([('model', 'like', 'device.')])
        self.view_status = len(views) >= 5
        log_lines.append(f'视图文件: {"✓" if self.view_status else "✗"} ({len(views)} 项)')
        
        # 计算总体状态
        status_count = sum([
            self.api_config_status,
            self.permission_status, 
            self.role_status,
            self.department_status,
            self.post_status,
            self.view_status
        ])
        
        if status_count == 6:
            self.init_status = 'completed'
            log_lines.append('\n✅ 系统已完全初始化')
        elif status_count >= 3:
            self.init_status = 'partial'
            log_lines.append('\n⚠️ 系统部分初始化')
        elif status_count > 0:
            self.init_status = 'partial'
            log_lines.append('\n⚠️ 系统部分初始化')
        else:
            self.init_status = 'not_init'
            log_lines.append('\n❌ 系统未初始化')
        
        self.init_log = '\n'.join(log_lines)

    def action_check_status(self):
        """检查状态"""
        self._check_init_status()
        return {
            'type': 'ir.actions.client',
            'tag': 'display_notification',
            'params': {
                'title': '状态检查完成',
                'message': '已更新所有状态信息',
                'type': 'success'
            }
        }

    def action_reinit(self):
        """重新初始化"""
        try:
            log_lines = ['=== 开始重新初始化 ===']
            
            # 导入初始化函数
            from ..hooks import (
                _create_api_config,
                _create_permissions, 
                _create_roles,
                _create_departments,
                _create_posts
            )
            
            # 执行初始化
            log_lines.append('创建API配置...')
            _create_api_config(self.env)
            
            log_lines.append('创建权限数据...')
            _create_permissions(self.env)
            
            log_lines.append('创建角色数据...')
            _create_roles(self.env)
            
            log_lines.append('创建部门数据...')
            _create_departments(self.env)
            
            log_lines.append('创建岗位数据...')
            _create_posts(self.env)
            
            log_lines.append('✅ 重新初始化完成！')
            
            # 更新状态
            self._check_init_status()
            
            # 添加初始化日志
            self.init_log = self.init_log + '\n\n' + '\n'.join(log_lines)
            
            return {
                'type': 'ir.actions.client',
                'tag': 'display_notification',
                'params': {
                    'title': '初始化成功',
                    'message': '系统数据已重新初始化完成',
                    'type': 'success'
                }
            }
            
        except Exception as e:
            error_msg = f'初始化失败: {str(e)}'
            _logger.error(error_msg, exc_info=True)
            
            self.init_log = (self.init_log or '') + f'\n\n❌ {error_msg}'
            
            return {
                'type': 'ir.actions.client',
                'tag': 'display_notification',
                'params': {
                    'title': '初始化失败',
                    'message': error_msg,
                    'type': 'danger'
                }
            }

    def action_load_views(self):
        """加载视图文件"""
        try:
            log_lines = ['=== 开始加载视图文件 ===']
            
            # 加载视图的实现
            self._load_device_views()
            
            log_lines.append('✅ 视图文件加载完成！')
            
            # 更新状态
            self._check_init_status()
            
            # 添加日志
            self.init_log = self.init_log + '\n\n' + '\n'.join(log_lines)
            
            return {
                'type': 'ir.actions.client',
                'tag': 'display_notification',
                'params': {
                    'title': '视图加载成功',
                    'message': '所有视图文件已加载完成',
                    'type': 'success'
                }
            }
            
        except Exception as e:
            error_msg = f'视图加载失败: {str(e)}'
            _logger.error(error_msg, exc_info=True)
            
            return {
                'type': 'ir.actions.client', 
                'tag': 'display_notification',
                'params': {
                    'title': '视图加载失败',
                    'message': error_msg,
                    'type': 'danger'
                }
            }

    def _load_device_views(self):
        """动态加载设备相关视图"""
        # 这里可以动态创建视图定义
        # 或者加载XML文件
        IrUiView = self.env['ir.ui.view']
        
        view_definitions = self._get_view_definitions()
        
        for view_data in view_definitions:
            existing = IrUiView.search([
                ('name', '=', view_data['name']),
                ('model', '=', view_data['model'])
            ], limit=1)
            
            if not existing:
                IrUiView.create(view_data)
                _logger.info(f'创建视图: {view_data["name"]}')

    def _get_view_definitions(self):
        """获取视图定义"""
        return [
            {
                'name': 'device.user.role.tree',
                'model': 'device.user.role',
                'type': 'tree',
                'arch': '''
                    <tree>
                        <field name="name"/>
                        <field name="code"/>
                        <field name="description"/>
                        <field name="sequence"/>
                        <field name="data_scope"/>
                        <field name="active"/>
                        <field name="create_time"/>
                    </tree>
                '''
            },
            {
                'name': 'device.user.role.form',
                'model': 'device.user.role',
                'type': 'form',
                'arch': '''
                    <form>
                        <sheet>
                            <group>
                                <group>
                                    <field name="name"/>
                                    <field name="code"/>
                                    <field name="sequence"/>
                                </group>
                                <group>
                                    <field name="active"/>
                                    <field name="data_scope"/>
                                </group>
                            </group>
                            <group>
                                <field name="description"/>
                            </group>
                            <notebook>
                                <page string="权限分配" name="permissions">
                                    <field name="permission_ids" widget="many2many_checkboxes"/>
                                </page>
                                <page string="数据权限" name="data_permissions">
                                    <field name="department_ids" widget="many2many_checkboxes"/>
                                </page>
                            </notebook>
                        </sheet>
                    </form>
                '''
            }
            # 可以添加更多视图定义
        ]
